package com.mhl.campuscabinet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.mhl.adapter.FragmentAdapter;
import com.mhl.adapter.ProductAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.Tag;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RecmFragment extends Fragment {

    TextView search;
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    // 目前顶部Tab标签在此写死，后续需要客户端向服务器请求所有标签并加载到titles的List中
    //private String [] title={"猜你喜欢","羽毛球","乒乓球","手机","劳力士","雨伞","保温杯"};
    //test
    private String [] title={"recommend","book","sports","study","stationery","electric","daily","food","clothe"};
    List<String> titles = new ArrayList<>();
    List<Fragment> fragments = new ArrayList<>();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recm, container, false);
        tabLayout = view.findViewById(R.id.tab_layout);
        tabLayout.setTabMode(tabLayout.MODE_SCROLLABLE);
        viewPager2 = view.findViewById(R.id.view_pager);
        for(int i = 0; i < title.length; i++) {
            // 添加标题
            titles.add(title[i]);
            // 添加碎片
            fragments.add(new TabFragment(title[i]));
        }
        // 实例化适配器
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getActivity().getSupportFragmentManager(),
                getActivity().getLifecycle(), fragments);
        // 设置适配器
        viewPager2.setAdapter(fragmentAdapter);
        viewPager2.setOffscreenPageLimit(1);
        // 关联标签导航和ViewPager
        new TabLayoutMediator(tabLayout, viewPager2,false, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull @NotNull TabLayout.Tab tab, int position) {
                tab.setText(titles.get(position));
            }
        }).attach();
        search = view.findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),ListActivity.class);
                startActivity(intent);
            }
        });

        Button test = view.findViewById(R.id.test);
        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),ProductActivity.class);
                //传递商品详细信息
                intent.putExtra("price",3600.00);
                intent.putExtra("username","name1");
                intent.putExtra("info","我是一件物品");
                intent.putExtra("date","2021-10-01");

                startActivity(intent);
            }
        });
        // Inflate the layout for this fragment


        //todo ip
        OkHttpUtils.sendOkHttpRequest(LocalData.getInstance().getIp()+"tag/list", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String data = response.body().string();
                int state = 1;

                try {
                    JSONObject userJson = new JSONObject(data);
                    state = userJson.getInt("errcode");
                    if(state != 0){
                        //Toast.makeText(LoginActivity.this, "Can't find this user", Toast.LENGTH_SHORT).show();
                        System.out.println("load tag failed");
                    }
                    else{
                        JSONObject tagJson = new JSONObject(data);
                        JSONArray tagArrayInfo = tagJson.getJSONArray("data");
                        for (int i = 0; i < tagArrayInfo.length(); i++) {
                            JSONObject tag = tagArrayInfo.getJSONObject(i);
                            int id = tag.getInt("id");
                            String name = tag.getString("name");
                            int merchandise_number = tag.getInt("merchandise_number");
                            int user_like = tag.getInt("user_like");
                            String description = tag.getString("description");
                            LocalData local_data = LocalData.getInstance();
                            local_data
                                    .TagList
                                    .add(new Tag(id, user_like, merchandise_number, name, description));
                            System.out.println("load tag succeeded");
                            System.out.println("tag" + i + ": " + local_data.TagList.get(i).getName());
                        }
//
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });




        return view;
    }


}